package com.example.sqliterecyclerview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class studentAdapter extends RecyclerView.Adapter<StudentViewHolder> {
    private Context context;
    private List<Student> studentList;

    public studentAdapter(Context context, List<Student> studentList) {
        this.context = context;
        this.studentList = studentList;
    }

    @NonNull
    @Override
    public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.student_item,parent,false);
        StudentViewHolder holder = new StudentViewHolder(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull StudentViewHolder holder, @SuppressLint("RecyclerView") int position) {
        Student student = studentList.get(position);
        holder.tvNo.setText(student.getStuno());
        holder.tvName.setText(student.getName());
        holder.tvAge.setText(String.valueOf(student.getAge()));
        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MySQLiteOpenHelper helper = new MySQLiteOpenHelper(context,"stu.db",null,1);
                SQLiteDatabase writableDatabase = helper.getWritableDatabase();
                String where = "stuno = " + student.getStuno();
                writableDatabase.delete("student",where,null);
                writableDatabase.close();
                studentList.remove(position);
                notifyDataSetChanged();
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("STUNO",student.getStuno());
                intent.putExtra("NAME",student.getName());
                intent.putExtra("AGE",student.getAge());
                intent.setClass(context,EditActivity.class);
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return studentList.size();
    }
}
